﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using XUCore.WeChat.Apis.Token;

namespace XUCore.WeChat
{
    /// <summary>
    /// 公众号AccessToken管理器
    /// </summary>
    public class WeChatTokenManager : IWeChatTokenManager
    {
        private readonly WeChatFuncs weChatFuncs;
        private readonly IServiceProvider serviceProvider;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="weChatFuncs"></param>
        /// <param name="serviceProvider"></param>
        public WeChatTokenManager(WeChatFuncs weChatFuncs, IServiceProvider serviceProvider)
        {
            this.weChatFuncs = weChatFuncs;
            this.serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 获取Access Token
        /// </summary>
        /// <param name="app">应用标识</param>
        /// <returns></returns>
        public virtual async Task<string> GetAccessTokenAsync(string app)
        {
            var options = weChatFuncs.GetWeChatOptions(app);

            if (options == null)
                throw new WeChatSdkException($"{nameof(WeChatTokenManager)}，App:{app}，获取微信配置失败。");

            string token = weChatFuncs.GetAccessTokenByAppId(options.AppId);
            if (string.IsNullOrEmpty(token))
            {
                ITokenApi tokenApi = serviceProvider.GetService<ITokenApi>();
                TokenApiResult result = await tokenApi.GetAsync(options.AppId, options.AppSecret);
                if (!result.IsSuccess())
                {
                    throw new WeChatSdkException(result.Message);
                }
                weChatFuncs.CacheAccessToken(options.AppId, result.AccessToken);
                return result.AccessToken;
            }
            return token;
        }
    }
}
